#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from wsgi import create_app
from app.models.work_order import WorkOrder
from app.models.user import User

def check_work_order_assignment():
    """检查工单分配情况"""
    app = create_app()
    
    with app.app_context():
        print("=== 工单4详细信息 ===")
        work_order = WorkOrder.query.get(4)
        if work_order:
            print(f"工单ID: {work_order.id}")
            print(f"工单标题: {work_order.title}")
            print(f"工单状态: {work_order.status}")
            print(f"创建者ID: {work_order.creator_id}")
            print(f"分配者ID: {work_order.assignee_id}")
            print(f"区域ID: {work_order.area_id}")
            print(f"组ID: {work_order.group_id}")
            
            # 获取创建者信息
            if work_order.creator_id:
                creator = User.query.get(work_order.creator_id)
                if creator:
                    print(f"创建者: {creator.username} ({creator.name}) - 角色: {creator.role}")
            
            # 获取分配者信息
            if work_order.assignee_id:
                assignee = User.query.get(work_order.assignee_id)
                if assignee:
                    print(f"分配者: {assignee.username} ({assignee.name}) - 角色: {assignee.role}")
            else:
                print("分配者: 未分配")
        else:
            print("工单4不存在")
        
        print("\n=== 维护人员信息 ===")
        workers = User.query.filter(User.role == 'worker').all()
        for worker in workers:
            print(f"用户ID: {worker.id}")
            print(f"用户名: {worker.username}")
            print(f"姓名: {worker.name}")
            print(f"角色: {worker.role}")
            print(f"区域ID: {worker.area_id}")
            print(f"组ID: {worker.group_id}")
            print("---")
        
        print("\n=== 权限分析 ===")
        if work_order:
            for worker in workers:
                can_view = (
                    work_order.creator_id == worker.id or 
                    work_order.assignee_id == worker.id
                )
                print(f"维护人员 {worker.username} 是否可以查看工单4: {can_view}")
                if not can_view:
                    print(f"  原因: 既不是创建者({work_order.creator_id})也不是分配者({work_order.assignee_id})")

if __name__ == '__main__':
    check_work_order_assignment()